package com.lsfb.signsys.compatible;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.lsfb.signsys.ApiException;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.StringReader;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by zgscwjm on 2018/3/27.
 */

public class MyGsonResponseBodyCoverter<T>  implements Converter<ResponseBody, T> {

    private final Gson gson;
    private final TypeAdapter<T> adapter;

    public MyGsonResponseBodyCoverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {

        String strResult = value.string();
        try {
            JSONObject jsonObject = new JSONObject(strResult);
            if (jsonObject.getInt("code")==200) {
//                JsonReader jsonReader =gson.newJsonReader(new StringReader(strResult));
                JsonReader jsonReader =gson.newJsonReader(new StringReader(jsonObject.getString("data")));
             T result =   adapter.read(jsonReader);
             if (jsonReader.peek()!=JsonToken.END_DOCUMENT){
                 throw new JsonIOException("JSON document was not fully consumed.");
             }
             return result;
            }else{
                throw new ApiException(jsonObject.getInt("code"),jsonObject.getString("msg"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
            throw new ApiException(0,"格式错误");
        }finally {
            value.close();
        }

    }
}
